; (function($, window) {

    QiniuUploaderNew = function(fileButton, opt) {

        //清空本地存储
        localStorage.removeItem("qzsq_qiniu_private_domain");
        localStorage.removeItem("qzsq_qiniu_uploadcategory");
        localStorage.removeItem("qzsq_apihost");

        //Override Or Upload
        var upTokenURL;
        var fileName = null;

        //是否覆盖上传
        if (opt.key) { 
            upTokenURL = opt.apiHost + "/api/qiniu/qiniutoken/CreateOverrideUploadToken?bucket=" +
            opt.bucket + "&key=" +
            opt.key;
        } else {
            upTokenURL = opt.apiHost + "/api/qiniu/qiniutoken/CreateUploadToken?bucket=" +
            opt.bucket + "&category=" +
            opt.category;
        }

        //--------------------------------------------获取上传token------------------------------
        var qiniuToken = null;
        var xmzyToken = localStorage.getItem("xmzy_user_token");
        $.ajax({
            url: upTokenURL,
            async: false,
            headers: { "Authorization": xmzyToken },
            success: function (data) {
                qiniuToken = data.result.token;
                localStorage.setItem("qzsq_qiniu_private_domain", data.result.domain);
            }
        });

        localStorage.setItem("qzsq_qiniu_uploadcategory", opt.category);
        localStorage.setItem("qzsq_apihost", opt.apiHost);

        var qiniuUpHosts = {
            "http": [
            "http://upload.qiniu.com",
            "http://up.qiniu.com"

            ],
            "https": [
            "https://up.qbox.me"
            ]
        };

        var changeUrlTimes = 0;

        //-------------------------------------------获取上传域名-----------------------------------
        var getUpHosts = function (uptoken) {
            var putPolicy = getPutPolicy(uptoken);
            var uphosts_url = window.location.protocol + "//uc.qbox.me/v1/query?ak=" + putPolicy.ak + "&bucket=" + putPolicy.bucket;

            $.ajax({
                url: uphosts_url,
                async: false,
                success: function (data) {
                    var res = data

                    qiniuUpHosts.http = getHosts(res.http.up);
                    qiniuUpHosts.https = getHosts(res.https.up);
                    var httpStorageKey = "qzsq_qiniubucket_http";
                    var httpsStorageKey = "qzsq_qiniubucket_https";

                    localStorage.setItem(httpStorageKey, res.http.up);
                    localStorage.setItem(httpsStorageKey, res.https.up);
                    resetUploadUrl();
                }
            });

            return qiniuUpHosts.http[0];
        };

        var resetUploadUrl = function () {
            var hosts = window.location.protocol === 'https:' ? qiniuUpHosts.https : qiniuUpHosts.http;
            var i = changeUrlTimes % hosts.length;
            qiniuUploadUrl = hosts[i];
            changeUrlTimes++;

        };

        var getHosts = function (hosts) {
            var result = [];
            for (var i = 0; i < hosts.length; i++) {
                var host = hosts[i];
                if (host.indexOf('-H') === 0) {
                    result.push(host.split(' ')[2]);
                } else {
                    result.push(host);
                }
            }
            return result;
        };

        var getPutPolicy = function (uptoken) {
            var segments = uptoken.split(":");
            var ak = segments[0];
            var putPolicy = JSON.parse(URLSafeBase64Decode(segments[2]));
            putPolicy.ak = ak;
            if (putPolicy.scope.indexOf(":") >= 0) {
                putPolicy.bucket = putPolicy.scope.split(":")[0];
                putPolicy.key = putPolicy.scope.split(":")[1];
            } else {
                putPolicy.bucket = putPolicy.scope;
            }
            return putPolicy;
        };

        var URLSafeBase64Decode = function (v) {
            v = v.replace(/_/g, '/').replace(/-/g, '+');
            return base64_decode(v);
        };

        var base64_decode = function (data) {
            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
            ac = 0,
            dec = "",
            tmp_arr = [];

            if (!data) {
                return data;
            }

            data += '';

            do { 
                h1 = b64.indexOf(data.charAt(i++));
                h2 = b64.indexOf(data.charAt(i++));
                h3 = b64.indexOf(data.charAt(i++));
                h4 = b64.indexOf(data.charAt(i++));

                bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

                o1 = bits >> 16 & 0xff;
                o2 = bits >> 8 & 0xff;
                o3 = bits & 0xff;

                if (h3 === 64) {
                    tmp_arr[ac++] = String.fromCharCode(o1);
                } else if (h4 === 64) {
                    tmp_arr[ac++] = String.fromCharCode(o1, o2);
                } else {
                    tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
                }
            } while (i < data.length);

            dec = tmp_arr.join('');

            return dec;
        };

        var url = getUpHosts(qiniuToken);

        var up = new QiniuNew({
            apiHost: opt.apiHost,
            category: opt.category,
            key: fileName,
            uptoken: qiniuToken,
            url: url,
            target: $(fileButton),
            accept:['png','jpg','jpeg'],
            maxSize:300,
            done: opt.onUploaded,
            onProgress: opt.onUploadProgress
        });

    }

})($, window);

